<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/17
 * Time: 13:15
 */

namespace App\Process;


use App\Sock\Logic\Game as GameLogic;
use EasySwoole\Core\Swoole\Process\AbstractProcess;
use EasySwoole\Core\Swoole\Time\Timer;
use Swoole\Process;
use EasySwoole\Config;
use EasySwoole\Core\Component\Di;
use EasySwoole\Core\Component\Cache\Cache;
use EasySwoole\Core\Swoole\ServerManager;

class OpenLottery extends AbstractProcess
{

    protected $db;

    public function __construct(string $processName, array $args, bool $async = true)
    {
        $dbConf = Config::getInstance()->getConf('database');
        $this->db = Di::getInstance()->get('MYSQL');
        $this->db->setPrefix($dbConf['prefix']);
        bcscale(2);

        parent::__construct($processName, $args, $async);
    }

    public function run(Process $process)
    {
        $unit_convert = function ($val) {
            switch ($val) {
                case 'small':
                    return 'dan';
                    break;
                case 'big':
                    return 'da';
                    break;
                case 'double':
                    return 'shuang';
                    break;
                case 'single':
                    return 'dan';
                    break;
                default:
                    return $val;
                    break;
            }

        };

        Timer::loop(30 * 1000, function () use ($unit_convert) {
            $this->db->where('bet_result', 0);
            $bet_log = $this->db->get('bet_log');
            $rate = Cache::getInstance()->get('game_rate');


            foreach ($bet_log as $item => $value) {
                $this->db->where('round_qishu', $value['round_turn']);
                $result = $this->db->getOne('game_round');
                $this->db->where('id', $value['user_id']);
                $user_info = $this->db->getOne('user');
                if (empty($result['round_result'])) {
                    continue;
                }


                $lottery = \App\Utility\MTool::handle_number($result['round_result']);
                if ($value['bet_type'] != 'two_star') {
                    if (isset($lottery[$value['bet_info']])) {
                        try {
                            if (in_array($value['bet_type'], $lottery[$value['bet_info']]['type'])) {
                                // 更新开奖结果

                                $this->db->where('bl_id', $value['bl_id']);
                                $get_coin = bcmul($value['bet_amount'], $rate[$unit_convert($value['bet_type']) . '_rate']);

                                $update = ['bet_result' => 1, 'bet_res_amount' => $get_coin];
                                $this->db->update('bet_log', $update);
                                // 更新用户金币

                                $return = ['lottery_amount' => $get_coin, 'commission_amount' => 0, 'final_amount' => $get_coin];

                                if ($user_info['inviter_id'] != 0) {
                                    $calc_data['lottery_amount'] = $get_coin;
                                    $return = $this->calc_commission($calc_data);

                                    // 更新代理 返点

                                    $this->db->startTransaction();
                                    $this->db->where('id', $value['user_id']);
                                    $update_agent = [
                                        'coin' => $this->db->inc($return['commission_amount']),
                                    ];
                                    $this->db->update('user', $update_agent);
                                    if ($this->db->getLastErrno() === 0) {
                                        $this->db->commit();
                                    } else {
                                        $this->db->rollback();
                                    }
                                }


                                $update_user = [
                                    'coin' => $this->db->inc($return['final_amount']),
                                ];
                                $this->db->where('id', $value['user_id']);
                                $this->db->update('user', $update_user);

                            } else {
                                $this->db->where('bl_id', $value['bl_id']);
                                $update = ['bet_result' => 2];
                                $this->db->update('bet_log', $update);
                            }
                        } catch (\Exception $e) {
                        }
                    }
                } else {
                    $bet_data = explode(',', $value['bet_data']);
                    $in_arr[0] = $lottery[$bet_data[0]]['value'];
                    $in_arr[1] = $lottery[$bet_data[1]]['value'];
                    $open_num = implode(',', $in_arr);
                    if ($value['bet_info'] == $open_num) {
                        // 更新开奖结果
                        $this->db->where('bl_id', $value['bl_id']);
                        $get_coin = bcmul($value['bet_amount'], $rate[$value['bet_type'] . '_rate']);
                        $update = ['bet_result' => 1, 'bet_res_amount' => $get_coin];
                        $this->db->update('bet_log', $update);

                        $return = ['lottery_amount' => $get_coin, 'commission_amount' => 0, 'final_amount' => $get_coin];


                        if ($user_info['inviter_id'] != 0) {
                            $calc_data['lottery_amount'] = $get_coin;
                            $return = $this->calc_commission($calc_data);

                            // 更新代理 返点

                            $this->db->startTransaction();
                            $this->db->where('id', $value['user_id']);
                            $update_agent = [
                                'coin' => $this->db->inc($return['commission_amount']),
                            ];
                            $this->db->update('user', $update_agent);
                            if ($this->db->getLastErrno() === 0) {
                                $this->db->commit();
                            } else {
                                $this->db->rollback();
                            }
                        }

                        // 更新用户金币


                        $update_user = [
                            'coin' => $this->db->inc($return['final_amount']),
                        ];
                        $this->db->where('id', $value['user_id']);

                        $this->db->update('user', $update_user);
                        //记录账户变动


                    } else {
                        $this->db->where('bl_id', $value['bl_id']);
                        $update = ['bet_result' => 2];
                        $this->db->update('bet_log', $update);

                    }
                }
            }

            $this->sendMessage(['payload' => json_encode(['type'=>'new_turn'])]);

        });



        // TODO: Implement run() method.
    }

    protected function calc_commission($data = [])
    {
        $rate = Cache::getInstance()->get('return_rate');
        //计算佣金
        $rate = $rate['return_rate'] / 100;

        // 奖金金额
        $lottery_num = $data['lottery_amount'];

        // 佣金金额
        $commission_amount = bcmul($lottery_num, $rate);

        // 最终奖金

        $final_amount = bcsub($lottery_num, $commission_amount);


        return ['lottery_amount' => $lottery_num, 'commission_amount' => $commission_amount, 'final_amount' => $final_amount];


    }

    protected
    function sendMessage($taskData = [])
    {
        $users = [];
        $roomid = isset($taskData['room_id']) ? $taskData['room_id'] : 0;
        if (!$roomid) {
            $room_list = Cache::getInstance()->get('room_list');
            foreach ($room_list as $item => $value) {
                $user[] = GameLogic::selectRoomFd($value['room_uuid']);
            }
            if (!empty($user)) {
                if (count($user) == 1) {
                    $users = $user[0];
                } else {
                    $users = [];
                    foreach ($user as $items => $list) {
                        foreach ($list as $ii => $vv) {
                            $users[] = $vv;
                        }
                    }
                }
            }
        } else {
            $users = GameLogic::selectRoomFd($roomid);
        }

        /** @var \swoole_websocket_server $server */
        $server = ServerManager::getInstance()->getServer();
        foreach ($users as $userFd) {
            $connection = $server->connection_info($userFd);
            if ($connection['websocket_status'] == 3) { // 用户正常在线时可以进行消息推送
                $server->push($userFd, $taskData['payload']);
            }
        }
    }

    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }

    public function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
    }


}